package com.jingtao.rabbitmq.producer;

import com.jingtao.rabbitmq.constant.RabbitMQConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * RabbitMQ消息生产者控制器
 */
@RestController
@RequestMapping("mq/rabbit")
@Slf4j
public class RabbitmqProducerController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送Hello World消息到队列
     */
    @GetMapping("hello/world")
    public String helloWorld() {
        String msg = "hello world rabbit!";
        rabbitTemplate.convertAndSend(RabbitMQConstants.HELLO_WORLD_QUEUE_NAME, msg);
        return "success~~";
    }

    /**
     * 发送工作队列消息
     */
    @GetMapping("work/queue")
    public String workQueue() {
        String msg = "hello world rabbit!";
        for (int i = 1; i <= 10; i++) {
            rabbitTemplate.convertAndSend(RabbitMQConstants.WORK_QUEUE_NAME, msg + i);
        }
        return "success~~";
    }

    /**
     * 发布订阅消息
     */
    @GetMapping("publisher/subscribe")
    public String publishSubscribe() {
        String msg = "publisher subscribe !";
        rabbitTemplate.convertAndSend(RabbitMQConstants.PUBLISHER_SUBSCRIBE_EXCHANGE_NAME, "", msg);
        return "success~~";
    }

    /**
     * 发送路由消息
     */
    @GetMapping("routing")
    public String routing() {
        String msg = "routing !";
        rabbitTemplate.convertAndSend(RabbitMQConstants.ROUTING_EXCHANGE_NAME, "error", msg);
        return "success~~";
    }

    /**
     * 发送主题消息
     */
    @GetMapping("topic/{key}")
    public String topic(@PathVariable String key) {
        String msg = "routing !";
        rabbitTemplate.convertAndSend(RabbitMQConstants.TOPIC_EXCHANGE_NAME, key, msg);
        return "success~~";
    }

//    @GetMapping("/direct/wx/transactional")
//    @Transactional(rollbackFor = Exception.class)
//    public String sendDirectMessageTransactional() {
//        // 手动添加一个异常，验证这条消息是否被消费到
//        rabbitTemplate.convertAndSend("direct_exchange", "WX", "hello world!");
//
//        // 人为制造一个异常
//        int i = 1 / 0;
//
//        log.info("开启事务消息机制");
//        try {
//            Thread.sleep(5000);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return "ok";
//    }




}
